import fitz
import os
import sys

import PyPDF2

from Crypto.Cipher import AES

old = sys.argv[1].split(".pdf")[0]
print(old)

# old = "《机器学习Python实践》"
new = old + "new"

doc = fitz.open(old+".pdf")
toc = doc.get_toc()
for i in toc:
    i[2] -= 1
# print(toc)
doc.close()

pdf_reader = PyPDF2.PdfReader(old+".pdf")

total_pages = pdf_reader.getNumPages()


pdf_writer = PyPDF2.PdfWriter()

delete_pages = [0,]
for i in range(total_pages):
    if i not in delete_pages:
        page = pdf_reader.pages[i]
        pdf_writer.add_page(page)

new_file = new + ".pdf"

with open(new_file,'wb') as f:
    pdf_writer.write(f)

# print(new_file)
try:
    doc = fitz.open(new_file)
    doc.set_toc(toc)
    doc.saveIncr()
    doc.close()
except ValueError:
    pass

# os.system("rm ./"+ old + ".pdf")
# os.system('rm "{}.pdf"'.format(old))
# os.system("mv "+new_file +" " + old + ".pdf")
os.system("mv '{}' '{}.pdf'".format(new_file,old))
# print("OK  " + "mv '{}' '{}.pdf'".format(new_file,old))
print("OK")